<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    @ok="handleSubmit"
    width="800px"
    title="添加表格控件"
    ok-text="保存"
  >
    <BasicForm @register="registerForm">
      <template #alarmColumnsSlot>
        <div
          v-for="(item, index) in selectColumnsList"
          :key="index"
          class="flex items-center w-full mt-10px mb-10px"
        >
          <FormItem class="w-2/5">
            <Select
              v-model:value="item.value"
              :options="columnsSelectoptions"
              :list-height="100"
            ></Select>
          </FormItem>

          <FormItem class="w-2/5 ml-10px">
            <Input v-model:value="item.value" :disabled="true" />
          </FormItem>

          <FormItem class="w-1/5 ml-10px">
            <Icon
              icon="ant-design:delete-outlined"
              @click="deleteColumnsClick(index)"
              size="20"
              color="#0960BD"
            />
          </FormItem>
        </div>
        <Button type="primary" size="small" @click="addColumnsClick">添加表头</Button>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { Select, Input, Button, FormItem } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import { getAlarmTypeList, getTrustedList } from '/@/api/thingsborad/alarm';
  import { getEntityDeviceList, getColumnsList } from '/@/api/thingsborad/entity/entity';
  import Icon from '/@/components/Icon/src/Icon.vue';
  import { ref } from 'vue';
  import { useDebounceFn } from '@vueuse/core';
  const emits = defineEmits(['success']);

  // 是否在仪表盘打开
  let isDashboard = ref<boolean>(false);

  //
  let selectColumnsList = ref<Array<any>>([
    {
      label: 'createdTime',
      value: 'createdTime',
    },
    {
      label: 'startTime',
      value: 'startTs',
    },
    {
      label: 'endTime',
      value: 'endTs',
    },
    {
      label: 'ackTime',
      value: 'ackTs',
    },
    {
      label: 'clearTime',
      value: 'clearTs',
    },
    {
      label: 'assignTime',
      value: 'assignTs',
    },
    {
      label: 'originator',
      value: 'originator',
    },
  ]);

  //表头选项
  let columnsSelectoptions = ref<Array<any>>([
    {
      label: 'assignee',
      value: 'assignee',
    },
    {
      label: 'status',
      value: 'status',
    },
    {
      label: 'severity',
      value: 'severity',
    },
    {
      label: 'type',
      value: 'type',
    },
    {
      label: 'originatorType',
      value: 'originatorType',
    },
    {
      label: 'originatorLabel',
      value: 'originatorLabel',
    },
    {
      label: 'originator',
      value: 'originator',
    },
    {
      label: 'assignTime',
      value: 'assignTs',
    },
    {
      label: 'clearTime',
      value: 'clearTs',
    },
    {
      label: 'ackTime',
      value: 'ackTs',
    },
    {
      label: 'endTime',
      value: 'endTs',
    },
    {
      label: 'startTime',
      value: 'startTs',
    },
    {
      label: 'createdTime',
      value: 'createdTime',
    },
  ]);

  // 表格数据
  let formOptions = ref<any>();
  let params = ref<any>({
    pageSize: 50,
    page: 0,
    textSearch: '',
    sortProperty: 'name',
    sortOrder: 'ASC',
    type: '',
  });

  //表格类型
  let schemas: FormSchema[] = [
    {
      field: 'Divider1',
      label: '表格类型',
      component: 'Divider',
      colProps: {
        span: 24,
      },
    },
    {
      field: 'tabletype',
      component: 'Select',
      label: '表格类型',
      required: true,
      defaultValue: 'ALARMS_TABLE',
      componentProps: {
        placeholder: '请选择表格类型',
        options: [
          {
            label: 'Alarms table',
            value: 'ALARMS_TABLE',
          },
          {
            label: 'Entities table',
            value: 'ENTITIES_TABLE',
          },
          {
            label: 'Timeseries table',
            value: 'TIMESERIES_TABLE',
          },
          {
            label: 'Persistent RPC table',
            value: 'PERSISTENT_RPC_TABLE',
          },
        ],
      },
    },
    // 告警表表单
    {
      field: 'Divider2',
      label: '名称',
      component: 'Divider',
      colProps: {
        span: 24,
      },
    },
    {
      field: 'tableTitle',
      component: 'Input',
      label: '表格名称标题',
      required: true,
      componentProps: {
        placeholder: '请输入表格名称',
      },
    },
    {
      ifShow: () => {
        return isDashboard.value === true;
      },
      field: 'Divider7',
      label: '告警源',
      component: 'Divider',
      colProps: {
        span: 24,
      },
    },

    {
      ifShow: () => {
        return isDashboard.value === true;
      },
      field: 'alarmDevice',
      label: '告警源设备',
      component: 'ApiSelect',
      componentProps: () => {
        return {
          placeholder: '请选择告警源设备',
          listHeight: 100,
          api: getEntityDeviceList,
          params: params.value,
          resultField: 'data',
          labelField: 'name',
          valueField: 'id',
          objectToJson: true,
          showSearch: true,
          onSearch: useDebounceFn((e) => {
            params.value.textSearch = e;
          }, 300),
          onChange: (e: string) => {
            if (e) {
              // seriesParams.value.payload.entityFilter.singleEntity = JSON.parse(e);
            } else {
              params.value.textSearch = '';
            }
          },
          onclick: async () => {
            //获取表头数据
            let data: any = {
              params: {
                attributes: true,
                timeseries: true,
              },
              data: {
                entityFilter: {
                  type: 'singleEntity',
                  singleEntity: {
                    entityType: 'DEVICE',
                    id: '63e416f1-fb97-11ee-bf35-41a6f6398a5e',
                  },
                },
                pageLink: {
                  pageSize: 100,
                  page: 0,
                  sortOrder: {
                    key: {
                      type: 'ENTITY_FIELD',
                      key: 'createdTime',
                    },
                    direction: 'DESC',
                  },
                },
              },
            };

            let columnsList = await getColumnsList(data);
            columnsList.attribute.forEach((item) => {
              columnsSelectoptions.value.push({
                label: item,
                value: item,
              });
            });
            columnsList.timeseries.forEach((item) => {
              columnsSelectoptions.value.push({
                label: item,
                value: item,
              });
            });
          },
          immediate: true,
        };
      },
      defaultValue: undefined,
      required: true,
    },
    {
      ifShow: () => {
        return isDashboard.value === true;
      },
      field: 'alarmColumns',
      component: 'Input',
      slot: 'alarmColumnsSlot',
      label: '表头',
      colProps: {
        span: 24,
      },
    },
    {
      ifShow: (val) => {
        return val.model.tabletype === 'ALARMS_TABLE';
      },
      field: 'Divider3',
      label: '筛选器',
      component: 'Divider',
      colProps: {
        span: 24,
      },
    },
    {
      ifShow: (val) => {
        return val.model.tabletype === 'ALARMS_TABLE';
      },
      field: 'alarmTypeList',
      component: 'CheckboxGroup',
      label: '告警状态列表',
      componentProps: {
        options: [
          {
            label: '激活',
            value: '激活',
          },
          {
            label: '已清除',
            value: '已清除',
          },
          {
            label: '已确认',
            value: '已确认',
          },
          {
            label: '未确认',
            value: '未确认',
          },
        ],
      },
    },
    {
      ifShow: (val) => {
        return val.model.tabletype === 'ALARMS_TABLE';
      },
      field: 'deepAlarmTypeList',
      component: 'CheckboxGroup',
      label: '警报严重性列表',
      componentProps: {
        options: [
          {
            label: '危险',
            value: '危险',
          },
          {
            label: '重要',
            value: '重要',
          },
          {
            label: '次要',
            value: '次要',
          },
          {
            label: '警告',
            value: '警告',
          },
          {
            label: '不确定',
            value: '不确定',
          },
        ],
      },
    },
    {
      ifShow: (val) => {
        return val.model.tabletype === 'ALARMS_TABLE';
      },
      field: 'alarmClassifyList',
      component: 'Select',
      label: '告警类型列表',
      required: true,
      componentProps: {},
    },
    {
      ifShow: (val) => {
        return val.model.tabletype === 'ALARMS_TABLE';
      },
      field: 'Trustee',
      component: 'Select',
      label: '受托人',
      required: true,
      componentProps: {},
    },
    {
      ifShow: (val) => {
        return val.model.tabletype === 'ALARMS_TABLE';
      },
      field: 'retrieveDeliveredAlerts',
      component: 'CheckboxGroup',
      label: '',
      componentProps: {
        options: [
          {
            label: '检索已传递的警报',
            value: '检索已传递的警报',
          },
        ],
      },
    },
    {
      ifShow: (val) => {
        return val.model.tabletype === 'ALARMS_TABLE';
      },
      field: 'Divider4',
      label: '表格功能按钮',
      component: 'Divider',
      colProps: {
        span: 24,
      },
    },
    {
      ifShow: (val) => {
        return val.model.tabletype === 'ALARMS_TABLE';
      },
      field: 'buttonFunction',
      component: 'CheckboxGroup',
      label: '',
      colProps: {
        span: 24,
      },
      defaultValue: [
        'displayAlarmActivity',
        'displayDetailedAlarmInformation',
        'AllowAllocationAlarms',
        'AllowConfirmationAlarms',
        'AllowClearingNotifications',
      ],
      componentProps: {
        options: [
          {
            label: '显示告警活动',
            value: 'displayAlarmActivity',
          },
          {
            label: '显示告警详细信息',
            value: 'displayDetailedAlarmInformation',
          },
          {
            label: '允许分配告警',
            value: 'AllowAllocationAlarms',
          },
          {
            label: '允许确认告警',
            value: 'AllowConfirmationAlarms',
          },
          {
            label: '允许清除告敬',
            value: 'AllowClearingNotifications',
          },
        ],
      },
    },
  ];

  const [registerForm, { validate, setFieldsValue, updateSchema }] = useForm({
    layout: 'vertical',
    schemas,
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });

  const [registerModal, { closeModal, setModalProps }] = useModalInner(async (data: any) => {
    

    if (data.whereFrom === 'dashboard') {
      //获取设备数据
      isDashboard.value = true;
    }

    if ('formData' in data) {
      setFieldsValue(data.formData.formOption);
    }
    // 获取 告警类型列表
    let params: any = {
      pageSize: 25,
      page: 0,
    };
    //数据清洗赋值
    let alarmType = await getAlarmTypeList(params);
    let dataList: Array<any> = [];
    

    alarmType.data.forEach((item) => {
      dataList.push({
        label: item.type,
        value: item.type,
      });
    });

    updateSchema({
      field: 'alarmClassifyList',
      componentProps: {
        mode: 'multiple',
        listHeight: '100',
        options: dataList,
      },
    });

    //获取受托人
    params = {
      pageSize: 50,
      page: 0,
      sortProperty: 'email',
      sortOrder: 'ASC',
    };

    let trustedList = await getTrustedList(params);
    dataList = [];
    trustedList.data.forEach((item) => {
      dataList.push({
        label: `姓名：${item.firstName} 邮箱：${item.email}`,
        value: item.id.id,
      });
    });
    updateSchema({
      field: 'Trustee',
      componentProps: {
        listHeight: '100',
        options: dataList,
      },
    });
    formOptions.value = data.formOptions;
    setModalProps({
      ...modalStyleSetting,
    });
  });

  const handleSubmit = async () => {
    let validateValue: any = await validate();
    if (isDashboard.value === true) {
      validateValue.alarmColumns = selectColumnsList.value;
    }
    

    emits('success', { formOption: validateValue });
    closeModal();
  };

  //添加表头
  function addColumnsClick() {
    selectColumnsList.value.push({
      label: '',
      value: '',
    });
  }

  //删除的表头
  function deleteColumnsClick(index: number) {
    selectColumnsList.value.splice(index, 1);
  }
</script>
